package com.ubaer.zsycz.ui.base.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;


import com.lsw.shareUser.ShareUserInfoUtil;
import com.lsw.util.AppManager;
import com.lsw.util.HideSoftKeyboardUtil;
import com.ubaer.zsycz.MyApplication;
import com.ubaer.zsycz.inject.components.DaggerFragmentComponent;
import com.ubaer.zsycz.inject.components.FragmentComponent;
import com.ubaer.zsycz.inject.modules.FragmentModule;
import com.ubaer.zsycz.ui.activity.LoginActivity;
import com.ubaer.zsycz.ui.base.presenter.IPresenter;

import java.lang.reflect.Field;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * author：JiaXing
 * e-mail：JiaXingGoo@gmail.com
 */
public abstract class BaseFragment<T extends IPresenter> extends Fragment {

    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";

    protected FragmentComponent mFragmentComponent;
    @Inject
    protected T mPresenter;
    //是否可见状态
    private boolean isVisible;
    //View已经初始化完成
    private boolean isPrepared;
    //是否第一次加载
    private boolean isFirstLoad;
    public Context mContext;
    private Unbinder unbinder;

    //布局文件的id
    protected abstract int getlayoutId();

    //注入
    protected abstract void initInjector();

    //初始化事件和获取数据, 在此方法中获取数据不是懒加载模式
    protected abstract void initEventAndData();

    //在此方法中获取数据为懒加载模式,如不需要懒加载,在initEventAndData获取数据
    protected abstract void lazyLoadData();

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.containsKey(STATE_SAVE_IS_HIDDEN)) {
            boolean isHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (isHidden) {
                ft.hide(this);
            } else {
                ft.show(this);
            }
            ft.commit();
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        isFirstLoad = true;
        View contentView = inflater.inflate(getlayoutId(), container, false);
        unbinder = ButterKnife.bind(this, contentView);
        isPrepared = true;
        mFragmentComponent = DaggerFragmentComponent.builder()
                .appComponent(MyApplication.getAppComponent())
                .fragmentModule(new FragmentModule(this)).build();
        initInjector();
        if (mPresenter != null) mPresenter.attachView(mContext, this);
        //初始化事件和获取数据, 在此方法中获取数据不是懒加载模式
        initEventAndData();
        //在此方法中获取数据为懒加载模式,如不需要懒加载,在initEventAndData获取数据
        lazyLoad();
        // 点击EditText以外的区域或者控件隐藏软键盘
        HideSoftKeyboardUtil.setupUI(contentView, (Activity) mContext);
        return contentView;
    }

    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirstLoad) return;
        isFirstLoad = false;
        lazyLoadData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInVisible();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            isVisible = false;
            onInVisible();
        } else {
            isVisible = true;
            onVisible();
        }
    }


    protected void onInVisible() {

    }

    protected void onVisible() {
        lazyLoad();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class
                    .getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用户单点登录
     */
    public void OpenLogin() {
        ShareUserInfoUtil.getInstance(mContext).clearCache();
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
        getActivity().finish();
        AppManager.getAppManager().finishAllActivity();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
        if (unbinder != null) unbinder.unbind();
    }

    /**
     * 隐藏输入法
     */
    public void hideSoftInput(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }
}
